<template>
  <div class="exercise-container">
    <h1 class="page-title">习题生成</h1>
    
    <!-- 输入区 -->
    <div class="input-section" v-if="!isGenerating && !exerciseResult">
      <div class="form-group">
        <label>学科</label>
        <select v-model="formData.subject">
          <option value="">请选择学科</option>
          <option 
            v-for="subject in subjects" 
            :key="subject.value" 
            :value="subject.value"
          >
            {{ subject.label }}
          </option>
        </select>
      </div>
      
      <div class="form-group">
        <label>知识点</label>
        <input 
          type="text" 
          v-model="formData.topic" 
          placeholder="请输入知识点，如：二次函数、牛顿第一定律"
        >
      </div>
      
      <div class="form-group">
        <label>题型选择</label>
        <div class="exercise-type-selector">
          <div 
            v-for="type in exerciseTypes" 
            :key="type.value"
            :class="['type-item', { active: selectedTypes.includes(type.value) }]"
            @click="toggleExerciseType(type.value)"
          >
            <div class="type-name">{{ type.label }}</div>
            <div class="type-desc">{{ type.description }}</div>
          </div>
        </div>
      </div>
      
      <div class="form-group">
        <label>难度</label>
        <div class="difficulty-slider">
          <input 
            type="range" 
            v-model.number="formData.difficulty" 
            min="1" 
            max="5"
            step="1"
          >
          <div class="difficulty-levels">
            <span 
              v-for="n in 5" 
              :key="n"
              :class="{ active: formData.difficulty >= n }"
            >
              {{ getDifficultyLabel(n) }}
            </span>
          </div>
        </div>
      </div>
      
      <div class="form-group">
        <label>生成数量</label>
        <div class="quantity-selector">
          <button 
            class="quantity-btn" 
            @click="decreaseQuantity"
            :disabled="formData.quantity <= 1"
          >
            -
          </button>
          <span class="quantity-value">{{ formData.quantity }}</span>
          <button 
            class="quantity-btn" 
            @click="increaseQuantity"
            :disabled="formData.quantity >= 10"
          >
            +
          </button>
        </div>
      </div>
      
      <div class="form-group">
        <label>附加要求</label>
        <textarea 
          v-model="formData.requirements" 
          placeholder="可选：输入对习题的特殊要求，如：包含实际应用场景、需要多步骤解题等"
          rows="3"
        ></textarea>
      </div>
      
      <button 
        class="generate-btn" 
        :disabled="!isFormValid" 
        @click="generateExercises"
      >
        确认输入，生成习题
      </button>
    </div>
    
    <!-- 加载状态 -->
    <div class="loading-section" v-if="isGenerating">
      <div class="loading-spinner"></div>
      <p>正在生成习题，请稍候...</p>
    </div>
    
    <!-- 结果预览区 -->
    <div class="result-section" v-if="exerciseResult">
      <div class="result-header">
        <h2>{{ exerciseResult.topic }} 习题</h2>
        <div class="result-meta">
          <span class="subject-badge">{{ getSubjectLabel() }}</span>
          <span class="difficulty-badge" :class="`level-${exerciseResult.difficulty}`">
            {{ getDifficultyLabel(exerciseResult.difficulty) }}
          </span>
          <span class="time">生成时间：{{ exerciseResult.createdAt }}</span>
        </div>
      </div>
      
      <div class="result-content">
        <div class="exercises-list">
          <div 
            v-for="(exercise, index) in exerciseResult.exercises" 
            :key="index"
            class="exercise-item"
          >
            <div class="exercise-header">
              <div class="exercise-number">{{ index + 1 }}</div>
              <div class="exercise-type">{{ getExerciseTypeLabel(exercise.type) }}</div>
            </div>
            
            <div class="exercise-content">
              <div class="question" v-html="formatContent(exercise.question)"></div>
              
              <div v-if="exercise.type === 'choice'" class="options">
                <div 
                  v-for="(option, optIndex) in exercise.options" 
                  :key="optIndex"
                  class="option-item"
                >
                  <span class="option-label">{{ String.fromCharCode(65 + optIndex) }}.</span>
                  <span v-html="formatContent(option)"></span>
                </div>
              </div>
            </div>
            
            <div class="exercise-footer">
              <button 
                class="toggle-answer-btn" 
                @click="toggleAnswer(index)"
              >
                {{ showAnswers[index] ? '隐藏答案' : '查看答案' }}
              </button>
            </div>
            
            <div v-if="showAnswers[index]" class="answer-section">
              <div class="answer-header">参考答案</div>
              <div class="answer-content" v-html="formatContent(exercise.answer)"></div>
              
              <div v-if="exercise.analysis" class="analysis-section">
                <div class="analysis-header">解析</div>
                <div class="analysis-content" v-html="formatContent(exercise.analysis)"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="result-actions">
        <button class="action-btn edit" @click="editExercises">编辑</button>
        <button class="action-btn save" @click="saveExercises">保存</button>
        <button class="action-btn export" @click="exportExercises">打印/导出</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useResourceStore } from '../../stores/resourceStore'
import apiService from '../../api'

const router = useRouter()
const resourceStore = useResourceStore()

// 表单数据
const formData = ref({
  subject: '',
  topic: '',
  difficulty: 3,
  quantity: 5,
  requirements: ''
})

// 学科选项
const subjects = [
  { label: '数学', value: 'math' },
  { label: '语文', value: 'chinese' },
  { label: '英语', value: 'english' },
  { label: '物理', value: 'physics' },
  { label: '化学', value: 'chemistry' },
  { label: '生物', value: 'biology' },
  { label: '历史', value: 'history' },
  { label: '地理', value: 'geography' },
  { label: '政治', value: 'politics' },
  { label: '信息技术', value: 'it' }
]

// 题型选项
const exerciseTypes = [
  { label: '选择题', value: 'choice', description: '单项选择题' },
  { label: '填空题', value: 'fill', description: '填写关键词或数值' },
  { label: '简答题', value: 'short', description: '简要回答问题' },
  { label: '计算题', value: 'calculation', description: '需要计算过程' },
  { label: '论述题', value: 'essay', description: '分析论证观点' }
]

// 已选择的题型
const selectedTypes = ref(['choice', 'fill'])

// 状态变量
const isGenerating = ref(false)
const exerciseResult = ref(null)
const showAnswers = reactive({})

// 表单验证
const isFormValid = computed(() => {
  return (
    formData.value.subject !== '' &&
    formData.value.topic.trim() !== '' &&
    selectedTypes.value.length > 0 &&
    formData.value.quantity > 0 &&
    formData.value.quantity <= 10
  )
})

// 切换题型选择
const toggleExerciseType = (type) => {
  const index = selectedTypes.value.indexOf(type)
  if (index === -1) {
    selectedTypes.value.push(type)
  } else {
    // 确保至少选择一种题型
    if (selectedTypes.value.length > 1) {
      selectedTypes.value.splice(index, 1)
    }
  }
}

// 获取难度标签
const getDifficultyLabel = (level) => {
  const labels = ['入门', '基础', '中等', '进阶', '挑战']
  return labels[level - 1] || ''
}

// 获取学科标签
const getSubjectLabel = () => {
  if (!exerciseResult.value) return ''
  const subject = subjects.find(s => s.value === exerciseResult.value.subject)
  return subject ? subject.label : ''
}

// 获取题型标签
const getExerciseTypeLabel = (type) => {
  const typeObj = exerciseTypes.find(t => t.value === type)
  return typeObj ? typeObj.label : ''
}

// 增加数量
const increaseQuantity = () => {
  if (formData.value.quantity < 10) {
    formData.value.quantity++
  }
}

// 减少数量
const decreaseQuantity = () => {
  if (formData.value.quantity > 1) {
    formData.value.quantity--
  }
}

// 格式化内容（处理数学公式等）
const formatContent = (content) => {
  if (!content) return ''
  
  // 这里可以添加对数学公式等特殊内容的处理
  // 实际项目中可能需要使用 MathJax 或 KaTeX 等库处理数学公式
  
  // 简单的换行处理
  return content.replace(/\n/g, '<br>')
}

// 切换显示答案
const toggleAnswer = (index) => {
  showAnswers[index] = !showAnswers[index]
}

// 生成习题
const generateExercises = async () => {
  try {
    isGenerating.value = true
    
    // 准备请求参数
    const params = {
      subject: formData.value.subject,
      topic: formData.value.topic,
      types: selectedTypes.value,
      difficulty: formData.value.difficulty,
      quantity: formData.value.quantity,
      requirements: formData.value.requirements.trim() || undefined
    }
    
    // 调用API生成习题
    // 实际项目中应该调用后端API
    // const response = await apiService.exercise.generate(params)
    
    // 模拟API响应
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟返回数据
    const mockExercises = []
    
    // 根据选择的题型生成对应数量的习题
    const typesToGenerate = [...selectedTypes.value]
    for (let i = 0; i < params.quantity; i++) {
      // 循环使用选择的题型
      const type = typesToGenerate[i % typesToGenerate.length]
      
      let exercise = {
        type,
        question: '',
        answer: '',
        analysis: ''
      }
      
      // 根据题型生成不同的习题内容
      if (type === 'choice') {
        if (params.subject === 'math') {
          exercise.question = `已知函数$f(x)=x^2-2x+1$，则$f(0)$的值为？`
          exercise.options = ['$0$', '$1$', '$2$', '$-1$']
          exercise.answer = 'B'
          exercise.analysis = '将$x=0$代入函数$f(x)=x^2-2x+1$，得$f(0)=0^2-2\\cdot0+1=1$，所以答案为B。'
        } else if (params.subject === 'physics') {
          exercise.question = '以下哪种现象不能用牛顿第一定律解释？'
          exercise.options = [
            '汽车急刹车时乘客向前倾',
            '物体在光滑平面上做匀速直线运动',
            '自由落体运动',
            '宇宙飞船在太空中做匀速直线运动'
          ]
          exercise.answer = 'C'
          exercise.analysis = '自由落体运动是在重力作用下的加速运动，应用牛顿第二定律解释，而非第一定律。'
        } else {
          exercise.question = `关于${params.topic}的基本概念，以下说法正确的是？`
          exercise.options = [
            '选项A的内容',
            '选项B的内容',
            '选项C的内容',
            '选项D的内容'
          ]
          exercise.answer = 'B'
          exercise.analysis = '选项B正确，因为...(详细解析)'
        }
      } else if (type === 'fill') {
        if (params.subject === 'math') {
          exercise.question = `已知等比数列$\\{a_n\\}$的前三项为$1,2,4$，则$a_5=\\_\\_\\_\\_$。`
          exercise.answer = '$16$'
          exercise.analysis = '等比数列$\\{a_n\\}$的前三项为$1,2,4$，可知公比$q=2$，则$a_5=a_1\\cdot q^{4}=1\\cdot 2^4=16$'
        } else {
          exercise.question = `${params.topic}的核心概念是\\_\\_\\_\\_。`
          exercise.answer = '答案内容'
          exercise.analysis = '解析说明...'
        }
      } else if (type === 'calculation') {
        if (params.subject === 'math') {
          exercise.question = `求函数$f(x)=\\ln(x^2+1)$在点$(0,0)$处的切线方程。`
          exercise.answer = '$y=0$'
          exercise.analysis = '解：$f^\\prime(x)=\\frac{2x}{x^2+1}$，所以$f^\\prime(0)=0$。\n因为$f(0)=0$，所以切线方程为$y-0=0\\cdot(x-0)$，即$y=0$。'
        } else if (params.subject === 'physics') {
          exercise.question = '一个质量为2kg的物体在水平面上受到5N的水平推力，已知物体与平面之间的动摩擦因数为0.2，重力加速度取10m/s²，求物体的加速度大小。'
          exercise.answer = '$1.5 m/s^2$'
          exercise.analysis = '解：物体受到的摩擦力$f=\\mu mg=0.2\\times 2\\times 10=4N$，\n合外力$F=5-4=1N$，\n由牛顿第二定律得加速度$a=\\frac{F}{m}=\\frac{1}{2}=0.5m/s^2$'
        } else {
          exercise.question = `计算问题：${params.topic}相关的计算...`
          exercise.answer = '计算过程和结果...'
          exercise.analysis = '详细解析步骤...'
        }
      } else if (type === 'short') {
        exercise.question = `简述${params.topic}的主要特点。`
        exercise.answer = '参考答案：1. 特点一；2. 特点二；3. 特点三...'
        exercise.analysis = '解析：该问题考察对概念的理解和表达能力...'
      } else if (type === 'essay') {
        exercise.question = `论述${params.topic}的发展历程及其重要意义。`
        exercise.answer = '参考答案：\n一、发展历程\n1. 早期阶段...\n2. 发展阶段...\n3. 现代应用...\n\n二、重要意义\n1. 理论意义...\n2. 实践价值...'
        exercise.analysis = '本题考察对知识体系的综合把握和论述能力...'
      }
      
      mockExercises.push(exercise)
    }
    
    const mockResponse = {
      subject: params.subject,
      topic: params.topic,
      difficulty: params.difficulty,
      exercises: mockExercises,
      createdAt: new Date().toLocaleString()
    }
    
    // 设置结果
    exerciseResult.value = mockResponse
    
    // 初始化答案显示状态
    mockExercises.forEach((_, index) => {
      showAnswers[index] = false
    })
    
    // 保存到状态管理
    resourceStore.setExerciseData(mockResponse)
    
  } catch (error) {
    console.error('生成习题失败:', error)
    // 可以在这里添加错误提示
  } finally {
    isGenerating.value = false
  }
}

// 编辑习题
const editExercises = () => {
  // 将当前结果数据填充到表单中
  formData.value.subject = exerciseResult.value.subject
  formData.value.topic = exerciseResult.value.topic
  formData.value.difficulty = exerciseResult.value.difficulty
  formData.value.quantity = exerciseResult.value.exercises.length
  
  // 设置已选择的题型
  const types = [...new Set(exerciseResult.value.exercises.map(e => e.type))]
  selectedTypes.value = types
  
  // 清空结果，返回编辑状态
  exerciseResult.value = null
}

// 保存习题
const saveExercises = async () => {
  try {
    // 调用API保存习题
    // 实际项目中应该调用后端API
    // await apiService.resource.save({
    //   type: 'exercise',
    //   data: exerciseResult.value
    // })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 显示成功提示
    alert('习题已保存到资源库')
    
  } catch (error) {
    console.error('保存习题失败:', error)
    // 可以在这里添加错误提示
  }
}

// 导出习题
const exportExercises = async () => {
  try {
    // 调用API导出习题
    // 实际项目中应该调用后端API
    // const response = await apiService.exercise.export(exerciseResult.value.id)
    // 
    // // 创建下载链接
    // const url = window.URL.createObjectURL(new Blob([response]))
    // const link = document.createElement('a')
    // link.href = url
    // link.setAttribute('download', `${exerciseResult.value.topic}_习题.pdf`)
    // document.body.appendChild(link)
    // link.click()
    // document.body.removeChild(link)
    
    // 模拟导出功能
    alert('导出功能在实际项目中需要后端支持')
    
  } catch (error) {
    console.error('导出习题失败:', error)
    // 可以在这里添加错误提示
  }
}

// 页面加载时检查是否有已生成的习题数据
onMounted(() => {
  const savedExercise = resourceStore.getExerciseData
  if (savedExercise && savedExercise.topic) {
    exerciseResult.value = savedExercise
    
    // 初始化答案显示状态
    savedExercise.exercises.forEach((_, index) => {
      showAnswers[index] = false
    })
  }
})
</script>

<style scoped>
.exercise-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-title {
  font-size: 1.8rem;
  margin-bottom: 24px;
  color: #333;
  font-weight: 600;
}

/* 输入区样式 */
.input-section {
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

input[type="text"],
textarea,
select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

input[type="text"]:focus,
textarea:focus,
select:focus {
  border-color: #4b6cb7;
  outline: none;
}

/* 题型选择器样式 */
.exercise-type-selector {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
}

.type-item {
  padding: 12px;
  border-radius: 8px;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: all 0.2s;
}

.type-item.active {
  background-color: #4b6cb7;
  color: white;
}

.type-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.type-desc {
  font-size: 0.85rem;
  opacity: 0.8;
}

/* 难度滑块样式 */
.difficulty-slider {
  margin-top: 10px;
}

.difficulty-slider input[type="range"] {
  width: 100%;
  height: 6px;
  -webkit-appearance: none;
  appearance: none;
  background: #ddd;
  outline: none;
  border-radius: 3px;
  margin-bottom: 12px;
}

.difficulty-slider input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #4b6cb7;
  cursor: pointer;
}

.difficulty-levels {
  display: flex;
  justify-content: space-between;
}

.difficulty-levels span {
  font-size: 0.85rem;
  color: #888;
  transition: all 0.2s;
}

.difficulty-levels span.active {
  color: #4b6cb7;
  font-weight: 500;
}

/* 数量选择器样式 */
.quantity-selector {
  display: flex;
  align-items: center;
  width: fit-content;
  border: 1px solid #ddd;
  border-radius: 6px;
  overflow: hidden;
}

.quantity-btn {
  width: 36px;
  height: 36px;
  background-color: #f5f5f5;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.quantity-btn:hover {
  background-color: #e0e0e0;
}

.quantity-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
}

.quantity-value {
  width: 40px;
  text-align: center;
  font-weight: 500;
}

/* 生成按钮样式 */
.generate-btn {
  width: 100%;
  padding: 12px;
  background-color: #4b6cb7;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.generate-btn:hover {
  background-color: #3b5998;
}

.generate-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

/* 加载状态样式 */
.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(75, 108, 183, 0.1);
  border-radius: 50%;
  border-top-color: #4b6cb7;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 结果预览区样式 */
.result-section {
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.result-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.result-header h2 {
  margin: 0 0 8px 0;
  font-size: 1.5rem;
  color: #333;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.subject-badge {
  background-color: #4b6cb7;
  color: white;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 500;
}

.difficulty-badge {
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 500;
  color: white;
}

.difficulty-badge.level-1 {
  background-color: #4CAF50;
}

.difficulty-badge.level-2 {
  background-color: #8BC34A;
}

.difficulty-badge.level-3 {
  background-color: #FFC107;
}

.difficulty-badge.level-4 {
  background-color: #FF9800;
}

.difficulty-badge.level-5 {
  background-color: #F44336;
}

.time {
  font-size: 0.9rem;
  color: #999;
}

/* 习题列表样式 */
.exercises-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.exercise-item {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
}

.exercise-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: #f9f9f9;
  border-bottom: 1px solid #eee;
}

.exercise-number {
  width: 24px;
  height: 24px;
  background-color: #4b6cb7;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.9rem;
  font-weight: 500;
  margin-right: 12px;
}

.exercise-type {
  font-size: 0.9rem;
  color: #666;
}

.exercise-content {
  padding: 16px;
}

.question {
  margin-bottom: 16px;
  line-height: 1.6;
}

.options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-item {
  display: flex;
  gap: 8px;
}

.option-label {
  font-weight: 500;
  color: #555;
}

.exercise-footer {
  padding: 12px 16px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
}

.toggle-answer-btn {
  padding: 6px 12px;
  background-color: #f0f5ff;
  color: #4b6cb7;
  border: 1px solid #4b6cb7;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s;
}

.toggle-answer-btn:hover {
  background-color: #e6f0ff;
}

/* 答案区域样式 */
.answer-section {
  padding: 16px;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
}

.answer-header,
.analysis-header {
  font-weight: 600;
  margin-bottom: 8px;
  color: #333;
}

.answer-content,
.analysis-content {
  line-height: 1.6;
  color: #555;
}

.analysis-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #ddd;
}

/* 结果操作按钮样式 */
.result-actions {
  display: flex;
  gap: 12px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.action-btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.action-btn.edit {
  background-color: #f5f5f5;
  color: #666;
}

.action-btn.edit:hover {
  background-color: #e0e0e0;
}

.action-btn.save {
  background-color: #4b6cb7;
  color: white;
}

.action-btn.save:hover {
  background-color: #3b5998;
}

.action-btn.export {
  background-color: #f0f5ff;
  color: #4b6cb7;
  border: 1px solid #4b6cb7;
}

.action-btn.export:hover {
  background-color: #e6f0ff;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .exercise-type-selector {
    grid-template-columns: 1fr;
  }
  
  .result-actions {
    flex-direction: column;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>